import Vue from 'vue'
import Router from 'vue-router'
import store from '../store'
import Login from '@/pages/login/Login'
import Person from '@/pages/person/Person'
import List from '@/pages/list/List'
import Report from '@/pages/report/Report'
import AboutUs from '@/pages/aboutUs/AboutUs'

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/',
      name: 'List',
      meta: {
        tabIdx: 1,
        requireAuth: true
      },
      component: List
    },
    {
      path: '/person',
      name: 'Person',
      meta: {
        tabIdx: 2,
        requireAuth: true
      },
      component: Person
    },
    {
      path: '/login',
      name: 'Login',
      component: Login
    },
    {
      path: '/report/:id',
      name: 'Report',
      component: Report,
      meta: {
        requireAuth: true
      }
    },
    {
      path: '/aboutUs',
      name: 'AboutUs',
      component: AboutUs,
      meta: {
        requireAuth: true
      }
    }
  ]
})

router.beforeEach((to, from, next) => {
  /* 路由登录拦截 */
  if (to.matched.some(r => r.meta.requireAuth)) {
    if (store.state.token) {
      next()
    } else {
      next({
        path: '/login',
        query: {redirect: to.fullPath}
      })
    }
  } else {
    next()
  }
})

router.afterEach((to, from) => {
  /* 页面跳转之前判断目的页面是否显示tab */
  store.commit('setTab', to.meta.tabIdx)
})

export default router
